// Note: this is config file
import { FastifyPluginOptions } from 'fastify'
import { FastifyHttpProxyOptions } from 'fastify-http-proxy'
import path from 'path'
import fs from 'fs'
import {InputOption, OutputOptions }from 'rollup'

const fsPromises = fs.promises

export type ShareConfig = {
	alias?: Record<string, string>,
  // path for static assets
  public?: string, 
  // extension support, default is ['js', 'mjs', 'vue', 'css',  'scss', ]
  extensions: string[]
}

export type ServerConfig = ShareConfig & FastifyPluginOptions & {
	
  // default root path for project
	root: string, 
  // proxy server config
	proxy?:FastifyHttpProxyOptions[],
  // port for dev server
	port: number,
  // open browser
	open?: boolean,
}

export type BuildConfig =  ShareConfig & {
	input?:InputOption,
	output?: OutputOptions
}

export type UserConfig = ServerConfig & BuildConfig

// 解析config 文件
export async function readConfig(configPath?: string): Promise<UserConfig> {
	const configFilePath = path.join(process.cwd(), configPath ? configPath : 'vite.config.js')
  await fsPromises.access(configFilePath)
  const config = require(configFilePath) as UserConfig
  return config
}

export function defaultConfig() {
 	return <UserConfig>{
		root: process.cwd(),
		port: 3000,
		input: 'src/main.js',
		output: {
			file: 'bundle.js',
			format: 'cjs'
		},
    extensions: ['mjs', 'js', 'vue']
	}
}
